<script setup lang="ts">
import type {FormInstance, FormRules} from "element-plus";
import {useGet} from "~/utils/utils";
import {useCountDown} from "~/hooks";
import {AGREEMENT} from "~/const/agreement";
const {countDown,restart,isRunning,stop}=useCountDown(120)
const phoneRef=ref<FormInstance>()
const phoneRules=reactive<FormRules>({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {validator:(rule, value, callback)=>{
      if(!/^1[3456789]\d{9}$/.test(value)){
        callback(new Error('手机号格式不正确'))
      }else{
        callback()
      }
    },trigger:'blur'
    }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
  agree:[{required:true,message:'请同意用户协议',trigger:'blur'},
    {validator:(rule, value, callback)=>{
      if(!value){
        callback(new Error('请同意用户协议'))
      }else{
        callback()
      }
    },trigger:'blur'
    }
  ],
})
const phone=reactive({
  phone:'',
  code:'',
  agree:false
})
const emailRef=ref<FormInstance>()
const emailRules=reactive<FormRules>({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {validator:(rule, value, callback)=>{
      if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)){
        callback(new Error('邮箱格式不正确'))
      }else{
        callback()
      }
    },trigger:'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入随机码', trigger: 'blur' },
  ],
})
const {data:random,refresh}=await useServerGet('/tools/getRandomCode')
const email=reactive({
  email:'',
  password:'',
  code:'',
  random_str:'',
})
const emailLogin=()=>{
  emailRef.value?.validate(async (valid,invalidFields) => {
    if (valid) {
      email.random_str=random.value.data.random_str;
      const {data,code}=await usePost('/user/loginByEmail',email);
      if(code==200){
        emailRef.value?.resetFields();
        emailRef.value?.clearValidate();
        login.setVisible(false);
        login.setToken(data?.token);
        login.setInfo(data?.user);
        ElMessage.success('登录成功');
        stop();
      }
    } else {
      showFieldsError(invalidFields)
    }

  });
}
const phoneLogin=()=>{
  phoneRef.value?.validate(async (valid,invalidFields) => {
    if (valid) {
      const {data,code}=await usePost('/user/loginByPhone',phone);
      if(code==200){
        phoneRef.value?.resetFields();
        phoneRef.value?.clearValidate();
        login.setVisible(false);
        login.setToken(data?.token);
        login.setInfo(data?.user);
        ElMessage.success('登录成功');
        stop();
      }
    } else {
      showFieldsError(invalidFields)
    }

  });

}
const login=useLoginStore()
const tab=ref('email')
const route=useRoute();
const router=useRouter()
const goRegister=()=>{
  login.setVisible(false);
  router.push({path:'/reg.html',params:{form:route.path}})
}
const sendCode=()=>{
  phoneRef.value?.validateField(['phone'],async (valid,invalidFields) => {
    if (valid) {
      const {data,code}=await usePost('/user/sendSms', {phone:phone.phone, sms_type:1,});
      if(code==200){
        restart()
      }
    } else {
      showFieldsError(invalidFields)
      return false;
    }
  });

}
const goto=(url:string)=>{
  login.setVisible(false);
  navigateTo(url);
}
watchEffect(()=>{
  if(login.visible){
    refresh&&refresh()
  }
})
</script>

<template>
<el-dialog v-model="login.visible" width="650" center title="登录">
  <div class="flex">
    <div class="pl-5 w-[200px]">
      <img src="/imgs/login.jpeg" alt="login" class="h-[274px]" />
    </div>
    <div class="w-[424px]">
      <el-tabs :stretch="true" class="px-5" v-model="tab">
        <el-tab-pane label="账号登录" name="email">
          <el-form label-width="0" label-suffix="：" size="default" class="h-[250px]" :model="email" :rules="emailRules" ref="emailRef">
            <el-form-item  prop="email">
              <el-input v-model="email.email"  clearable placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item  prop="password">
              <div class="flex w-full">
                <el-input type="password" v-model="email.password" clearable class="flex-1" placeholder="请输入密码"></el-input>
              </div>
            </el-form-item>
            <el-form-item  prop="code">
              <div class="flex w-full">
                <el-input v-model="email.code" class="flex-1" clearable  placeholder="请输入随机码"></el-input>
                <img :src="random?.data?.random_code_img" class="pl-2 w-[92px]" @click="refresh" alt="随机码"/>
              </div>
            </el-form-item>
            <div class="flex justify-between w-full mb-2 mt-5">
              <div @click="goRegister"><span class="text-xs text-blue-400">没有账号，去注册</span></div><NuxtLink><span class="text-xs text-gray-400" @click="goto('/forget.html')">忘记密码?</span></NuxtLink>
            </div>
            <el-form-item>
              <el-form-item prop="agree">
                <el-button type="primary" @click="emailLogin" size="large" class="w-full">登录</el-button>
                登录即表示您已阅读并同意<span class="text-blue-400 text-xs" @click="goto(AGREEMENT.用户服务协议)">《用户服务协议》</span>和<span class="text-blue-400 text-xs" @click="goto(AGREEMENT.隐私服务协议)">《隐私服务协议》</span>
              </el-form-item>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="手机号登录" name="phone">
          <el-form size="default" class="h-[250px]" label-width="0" :model="phone" :rules="phoneRules" ref="phoneRef">
            <el-form-item  prop="phone">
              <el-input v-model="phone.phone" clearable placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item  prop="code">
              <div class="flex w-full">
                <el-input v-model="phone.code" class="w-2/3" placeholder="请输入验证码" clearable></el-input>
                <el-button type="primary" class="ml-2" @click="sendCode" :disabled="isRunning">{{isRunning?`${countDown}s`:'获取验证码'}}</el-button>
              </div>
            </el-form-item>
            <div class="flex w-full text-[var(--el-color-primary)] mb-2 mt-[70px]">
              温馨提示：无需注册账户，手机可直接登录！
            </div>
            <el-form-item prop="agree">
              <el-button type="primary" @click="phoneLogin" size="large" class="w-full">登录</el-button>
              <el-checkbox v-model="phone.agree" class="text-xs">我已阅读并同意<span class="text-blue-400 text-xs" @click="goto(AGREEMENT.用户服务协议)">《用户服务协议》</span>和<span class="text-blue-400 text-xs" @click="goto(AGREEMENT.隐私服务协议)">《隐私服务协议》</span></el-checkbox>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <template #footer>
    <div class="dialog-footer">

    </div>
    <div>

    </div>
  </template>
</el-dialog>
</template>

<style scoped lang="scss">
.login {
  background-image: url('/imgs/login_bg.jpeg');
  background-size: 100% 100%;
  background-color: transparent;
}
</style>